import * as G2 from '@antv/g2';
import { useEffect } from "react";
import './error-metrics.less';

let chart: any = null;

function render(data: any[]) {
  let days: any = {}

  data.forEach((it: any) => {
    const d = it.time.substr(0, 10)
    if (days[d]) {
      days[d] += 1;
    } else {
      days[d] = 1
    }
  })

  data = Object.keys(days).map((key) => {
    return {
      time: key,
      value: days[key]
    }
  })

  if (chart === null) {
    chart = new G2.Chart({
      container: 'code-error-bar-chart',
      height: 280,
      width: 1200,
      forceFit: true,
      padding: [40, 40, 40, 40],
    });
  }

  chart.source(data);

  chart.axis('time', {
    // label: {
    //   textStyle: {
    //     fill: '#00000'
    //   }
    // }
  });

  chart.axis('value', {
    // label: {
    //   textStyle: {
    //     fill: '#00000'
    //   }
    // }
  });

  chart.interval().position('time*value');
  chart.render();
}

interface ErrorMetricsProps {
  metrics: any[]
}

export default function CodeErrorBarChart(props: ErrorMetricsProps) {
  useEffect(() => {
    render(props.metrics);
    return function () {
      chart.destroy();
      chart = null;
    }
  }, [props.metrics])

  return (
    <div
      className={"metrics-chart"}
      style={{ marginTop: 20, }}
      id="code-error-bar-chart"
    />
  )
}